# 导包
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression,Lasso,Ridge
from sklearn.metrics import mean_squared_error

# 创建数据
np.random.seed(222)
x =np.random.uniform(-3,3,size=100)
print(x.shape)
y = 0.5*x**2+x+2+0.1*np.random.normal(0,1,size=100)

# 模型训练
X = x.reshape(-1,1)
# print(X.shape)
# X2 = np.hstack([X,X**2])
X3 = np.hstack([X,X**2,X**3,X**4,X**5,X**6,X**7,X**8,X**9,X**10])
# LR =LinearRegression()
LR =Lasso(alpha=2)
# LR =Ridge()
LR.fit(X3,y)
print(LR.coef_)
# 模型预测
y_predict =LR.predict(X3)

# 模型评估
print(mean_squared_error(y, y_predict))

# 可视化
plt.scatter(x,y)
plt.plot(np.sort(x),y_predict[np.argsort(x)],color = 'r')
plt.show()